import { ref } from 'vue';
import { defineStore } from 'pinia';
import type { Ref } from 'vue';


export const FilmDataObj = defineStore('liustore', () => {
    // 跳转座位详情页携带数据
    let FilmImg: Ref<string> = ref(localStorage.getItem('FilmImg') || '');

    let FilmObj: Ref<object> = ref(JSON.parse(localStorage.getItem('FilmObj') || '{}'))

    // 全部订单数据
    let OrdersArray: Ref<Array<object>> = ref(JSON.parse(localStorage.getItem('OrdersArray') || '[]'));




    // 当前订单数据
    let CurrentOrders: Ref<object> = ref(JSON.parse(localStorage.getItem('CurrentOrders') || '{}'))


    // 登录后获取订单数据

    const updateOrdersArray = () => {
        const token = localStorage.getItem("token2")
        OrdersArray.value = JSON.parse(localStorage.getItem(`${token}`) || '[]')
    }


    //    添加选座详情页数据
    const ChooseYourSeat = (img: string, dataobj: object) => {
        FilmImg.value = img;
        FilmObj.value = { ...dataobj };
        console.log("pinia", FilmImg.value, FilmObj.value);

    };



    // 支付订单数据
    const PayForTheOrder = (item: object) => {

        CurrentOrders.value = item;
        console.log("CurrentOrders变更", CurrentOrders.value);


    }

    // 加入全部订单数据

    const addOrdersArray = (item: object) => {
        console.log("pinia", item);

        let user = localStorage.getItem("token2")

        OrdersArray.value = JSON.parse(localStorage.getItem(`${user}`) || '[]')

        // OrdersArray.value = [...OrdersArray.value,item]
        OrdersArray.value.push(item)
        console.log("OrdersArray", OrdersArray.value);
        CurrentOrders.value = item
        localStorage.setItem("OrdersArray", JSON.stringify(OrdersArray.value))

        localStorage.setItem(`${user}`, JSON.stringify(OrdersArray.value))


    }

    // 修改订单数据状态

    const switchOrdersArray = (key: number) => {
        console.log("key", key);

        let user = localStorage.getItem("token2")

        // OrdersArray.value = [...OrdersArray.value,item]
        OrdersArray.value = OrdersArray.value.map((itm) => {
            return itm.OrderNumber == key ? { ...itm, isPay: true } : itm
        })
        console.log("OrdersArray", OrdersArray.value);

        localStorage.setItem("OrdersArray", JSON.stringify(OrdersArray.value))

        localStorage.setItem(`${user}`, JSON.stringify(OrdersArray.value))


    }




    return { FilmImg, ChooseYourSeat, FilmObj, PayForTheOrder, CurrentOrders, addOrdersArray, OrdersArray, switchOrdersArray,updateOrdersArray };
});
